package org.com.practice.nacos.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class HelloController {

    @Autowired
    private DiscoveryClient client;
    @Autowired
    private RestTemplate restTemplate;
    private final String serviceName = "nacos-provider";
    @GetMapping("/info")
    public String info() {
        List<ServiceInstance> instances = client.getInstances(serviceName);
        StringBuilder sb = new StringBuilder();
        instances.forEach(instance -> {
            sb.append("serviceId:").append(instance.getServiceId()).append(", host:").append(instance.getHost())
                    .append(".port:").append(instance.getPort()).append("<br/>");
        });
        return sb.toString();
    }

    @GetMapping("/hello")
    public String hello() {
        List<ServiceInstance> instances = client.getInstances(serviceName);
        ServiceInstance serviceInstance = instances.stream().findAny().orElseThrow(() -> new IllegalStateException("no " + serviceName + " instance available"));
        return restTemplate.getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/hello/nacos", String.class);
    }
}
